#include "filereader.h"

FileReader::FileReader(QHostAddress address, int port) : address(address), port(port)
{
    this->socket=new QTcpSocket(this);
    connect(this->socket, SIGNAL(readyRead()), this,SLOT(read()));
    connect(this->socket,SIGNAL(connected()),this,SLOT(connected()));
    fileBuffer=new QByteArray();
    receivingFile=false;
    buffer=new QBuffer(&response);
    buffer->open(QIODevice::WriteOnly);
    socket->connectToHost(address,port);
    out.setDevice(buffer);
    out.setVersion(QDataStream::Qt_4_0);
    out << (quint64)0; //placeholder for size do not forget
    blockSize=0;
    qDebug()<<"starting size"<<response.size();
}

void FileReader::read() {
    QDataStream in(socket);
    in.setVersion(QDataStream::Qt_4_0);

    if (blockSize == 0) {
        if (socket->bytesAvailable() < (int)sizeof(quint64))
            return;

        in >> blockSize;
        qDebug()<<"awaiting block of size "<<blockSize;
    } else {
        qDebug()<<socket->bytesAvailable() <<blockSize;
    }
   qDebug()<<socket->bytesAvailable() <<blockSize;
    if (socket->bytesAvailable() < blockSize) {
        return;
    } else {
       qDebug()<<"got it all";
    }
    //QByteArray result=socket->readAll();
    QByteArray result;
    in >> result;
    qDebug()<<" "<<result.size();
    fileBuffer->append(result);
    complete();
}

void FileReader::requestFile(int mediaID) {
    receivingFile=true;
    QByteArray s;
    s+="send "+QString::number(mediaID);
    out<<s;
    write();
}

void FileReader::getListing(QString param) {
    QByteArray s;
    s+="list "+param;
    out<<s;
    qDebug()<<"size is now"<<buffer->size();
    write();
}

//still trying to figure out how to create a streaming QIODevice
QIODevice * FileReader::getStreamingDevice() {
    return NULL;
}

void FileReader::complete() {
   // disconnect(socket,SIGNAL(disconnected()),this,SLOT(complete()));
    //socket->close();
    if(receivingFile) {
        emit downloadComplete(fileBuffer);
        receivingFile=false;
    } else {
        emit completed(fileBuffer);
    }
    fileBuffer->clear();
}

QImage FileReader::toImage() {

}

QByteArray * FileReader::getData() {
    return fileBuffer;
}

void FileReader::connected() {
    write();
}

void FileReader::write() {
    if(socket->isOpen()&&response.size()>sizeof(quint64)) {
        out.device()->seek(0);
        //qDebug()<<"size is"<<sizeof(quint64)<<" "<<response.size();
        out<<((quint64)(response.size()- sizeof(quint64)));
        socket->write(response);
        response.clear();
        blockSize=0;
        out.device()->seek(0);
        out << (quint64)0; //placeholder for size do not forget
    }
}
